<template>
	<view>
		<view class="top-bg u-bg-primary"></view>
		<view class="u-m-l-20 u-m-r-20">
			<view class="u-bg-fff u-p-30 u-m-20">
				<view class="">
					<view class="u-tips-color u-font-15">
						账本管理
					</view>
				</view>
				<view class="u-flex u-row-between u-col-center u-m-t-30" @click="showPopupSheet">
					<view class="">
						<u-avatar :src="bookAvatar"></u-avatar>
					</view>
					<view class="u-font-12">
						{{bookName}}
					</view>
					<view class="">
						<u-tag text="默认账本" type="warning" mode="plain" shape="circle" size="mini" v-if="bdef" />
					</view>
					<view class="" v-if="isBookAuthorInfo.auth==2">
						<u-icon name="arrow-right" color="u-main-color" size="28"></u-icon>
					</view>
				</view>
			</view>

			<view class="u-m-20">
				<u-section title="成员管理" :arrow="false" :right="false"></u-section>
				<view class="u-flex u-col-center u-p-l-20 u-p-r-20 u-m-t-20" v-for="(item,i) in list" :key="i">
					<view class="u-m-r-20">
						<u-avatar :src="item.avatarUrl" size="mini"></u-avatar>
					</view>
					<view class="u-flex u-flex-1 u-row-between">
						<view class="u-content-color">
							{{item.reallyName}}
						</view>
						<view class="u-flex u-col-center" v-if="item.auth==2">
							<u-tag text="创建人" type="warning" mode="plain" shape="circle" size="mini" />
						</view>
						<view class="u-flex u-col-center" v-if="item.auth==1">
							<u-tag text="管理员" type="warning" mode="plain" shape="circle" size="mini" />
						</view>
						<view class=""
							v-if="(isBookAuthorInfo.auth==2)||(isBookAuthorInfo.auth==1&&item.auth!=1&&item.auth!=2)">
							<u-icon name="arrow-right" size="28" @click="showActionSheet(i)"></u-icon>
						</view>
					</view>
				</view>
			</view>

			<u-popup v-model="showPopup" mode="center" border-radius="20" :closeable="true" width="80%"
				:safe-area-inset-bottom="true">
				<view class="u-p-t-50 u-p-b-50 u-p-l-30 u-p-r-30">
					<view @click="chooseAvatar" class="u-m-l-40 u-m-r-40">
						<view class="u-flex u-row-center">
							<u-avatar :src="bookAvatar" size="large"></u-avatar>
						</view>
						<view class="u-flex u-row-center u-margin-10">
							<u-icon name="play-right-fill" size="18" label-size="24" top="1rpx" label="点击选择图片"
								label-pos="left"></u-icon>
						</view>
					</view>
					<view class="u-p-10 u-m-t-40 u-bg u-flex u-row-between u-col-center">
						<view class="u-flex-1 u-content-color u-font-md u-text-center">
							账本名
						</view>
						<view class="u-flex-2">
							<u-input v-model="bookName" type="text" placeholder="请输入内容" maxlength="25" :focus="inpFocus"
								confirm-type="提交" />
						</view>
					</view>
					<view class="u-p-10 u-m-t-40 u-bg u-flex u-row-between u-col-center">
						<view class="u-flex-1 u-content-color u-font-md u-text-center">
							每月预算
						</view>
						<view class="u-flex-2">
							<u-input v-model="budget" type="digit" placeholder="请输入每月预算" maxlength="25"
								:focus="inpFocus" confirm-type="提交" />
						</view>
					</view>
					<view class="u-p-10 u-m-t-40 u-bg u-flex u-row-between u-col-center">
						<view class="u-flex-1 u-content-color u-font-md height-70 u-text-center">
							默认账本
						</view>
						<view class="u-flex-2 u-flex u-col-center height-70">
							<u-switch v-model="def" active-color="#19be6b"></u-switch>
						</view>
					</view>
					<view class="u-p-10 u-m-t-40 u-bg u-flex u-row-between u-col-center">
						<view class="u-flex-1 u-content-color u-font-md height-70 u-text-center">
							邀请验证
						</view>
						<view class="u-flex-2 u-flex u-col-center height-70">
							<u-switch v-model="audit" :disabled="isAudit" active-color="#19be6b"></u-switch>
						</view>
					</view>
					<view class="u-p-10 u-m-t-40 u-bg u-flex u-row-between u-col-center">
						<view class="u-flex-1 u-content-color u-font-md height-70 u-text-center">
							私密账本
						</view>
						<view class="u-flex-2 u-flex u-col-center height-70">
							<u-switch v-model="search" active-color="#19be6b" @change="searchChange"></u-switch>
						</view>
					</view>
					<view class="u-m-t-30">
						<u-button :loading="isLoad" @click="submit" type="success"
							:custom-style="{'border-radius':'20rpx'}" throttle-time="500" hover-class="none">提
							交</u-button>
					</view>
				</view>
			</u-popup>
			<view v-if="isBookShow">
				<view class="u-flex u-row-between">
					<view class="u-p-40" v-if="isBookAuthorInfo.auth==2||isBookAuthorInfo.auth==1">
						<u-button type="success" open-type="share" @click="shareFriends"
							:custom-style="{'border-radius':'20rpx'}" throttle-time="500"
							hover-class="none">邀请好友参与记账</u-button>
					</view>
					<view class="u-p-40" v-if="isBookAuthorInfo.auth==0||isBookAuthorInfo.auth==1">
						<u-button type="success" :custom-style="{'border-radius':'20rpx'}" throttle-time="500"
							hover-class="none" @click="exitBook">退出账本</u-button>
					</view>
				</view>
			</view>
		</view>
		<u-modal v-model="showExitBook" :content="exitBookContent" title="退出账本提示" :show-cancel-button="true"
			confirm-color="#ff0000" :content-style="{color: 'red'}" :mask-close-able="true"
			@confirm="confirmExitBook"></u-modal>
		<u-action-sheet :list="actionList" v-model="showAction" border-radius="20" :safe-area-inset-bottom="true"
			@click="touchList"></u-action-sheet>
		<u-top-tips ref="uTips"></u-top-tips>
	</view>
</template>

<script>
	let _this;
	export default {
		data() {
			return {
				showPopup: false,
				name: '',
				def: false,
				bdef: false,
				isLoad: false,
				bookId: '',
				list: [],
				actionList: [],
				bookAvatar: '',
				bookName: '',
				showAction: false,
				actionIndex: 0,
				isCreator: false,
				budget: '',
				audit: false,
				auditEmp: false,
				isAudit: false,
				search: false,
				isBookAuthorInfo: '',
				isBookShow: false,
				exitBookContent: '',
				showExitBook: false,
				userId: ''
			}
		},
		created() {
			uni.$on('uAvatarCropper', path => {
				uni.showLoading({
					title: '正在上传...'
				})
				_this.bookAvatar = path;
				console.log("文件地址：" + _this.bookAvatar)
				uni.uploadFile({
					url: 'https://account-book-front.1900shop.online/api/file/upload',
					filePath: path,
					name: 'file',
					formData: {
						type: 1
					},
					success: (response) => {
						console.log("响应：" + JSON.stringify(response));
						const res = JSON.parse(response.data);
						if (res.status == 200) {
							_this.bookAvatar = res.message;
							_this.$u.toast('上传成功')
						} else {
							_this.$u.toast('文件上传失败')
						}
					},
					fail() {
						_this.$u.toast('上传失败')
					},
					complete() {
						uni.hideLoading()
					}
				});
			})
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#42b479',
				animation: {
					duration: 400,
					timingFunc: 'easeIn'
				}
			})
		},
		onLoad(e) {
			_this = this;
			_this.bookId = e.bookId
			_this.isBookAuthor()
			_this.get()
		},
		methods: {
			//编辑账本是否有编辑权限
			async isBookAuthor() {
				await _this.$u.api.isBookAuthor({
					bookId: _this.bookId
				}).then(res => {
					console.log("编辑账本是否有编辑权限" + JSON.stringify(res))
					_this.isBookAuthorInfo = res;
				});
			},
			//点击退出账本
			exitBook() {
				_this.showExitBook = true
				_this.exitBookContent = "您正在退出账本《" + _this.bookName + "》,重新加入将恢复账本"
			},
			//二次确认确定退出账本
			confirmExitBook() {
				_this.showExitBook = false
				_this.signOutBook()
			},
			//用户退出账本
			async signOutBook() {
				await _this.$u.api.signOutBook({
					bookId: _this.bookId
				}).then(res => {
					_this.goTabbarUrl('/pages/app/index')
				});
			},
			//点击账本编辑按钮
			showPopupSheet() {
				if (_this.isBookAuthorInfo.auth == 2) {
					_this.showPopup = true
				} else {
					_this.showPopup = false
				}
			},
			//查询账本下的账本信息和用户列表
			async get() {
				uni.showLoading({
					title: '正在加载'
				})
				await _this.$u.api.userGet({
					bookId: _this.bookId
				}).then(res => {
					console.log("查询账本下的账本信息和用户列表:" + JSON.stringify(res))
					_this.bookName = res.book.bookName
					_this.bookAvatar = res.book.bookAvatar
					_this.budget = res.bookUserQueryVos[0].budget
					_this.audit = res.book.userAudit == 1 ? true : false
					_this.auditEmp = res.book.userAudit == 1 ? true : false
					_this.search = res.book.showSearch == 1 ? true : false
					_this.list = res.bookUserQueryVos
					_this.isCreator = res.bookUserQueryVos[0].auth == 2 ? true : false
					_this.bdef = res.bookUserQueryVos[0].defaultBook == 1 ? true : false
					_this.def = res.bookUserQueryVos[0].defaultBook == 1 ? true : false
					//是否是私密账本
					if (_this.search) {
						_this.isBookShow = false
						_this.isAudit = true
						_this.audit = false
					} else {
						_this.isBookShow = true
						_this.isAudit = false
					}
				});
			},
			//是否分享
			shareFriends() {
				if (_this.isBookAuthorInfo.auth != 0) {
					console.log("分享跳转")
					_this.$u.mpShare = {
						title: '币迹',
						path: '/pages/app/index?bookId=' + _this.bookId + '&bookName=' + _this.bookName +
							'&inv=1&time=' +
							new Date().getTime(),
						imageUrl: 'https://account-book-cos.1900shop.online/static/images/edit/金融.png'
					}
				}
			},
			//更新账本
			async submit() {
				_this.isLoad = true
				uni.showLoading({
					title: '正在更新账本...'
				})
				if (!_this.bookName) {
					_this.$u.toast('请输入账本名')
					_this.isLoad = false
					return
				}
				//是否是私密账本
				if (_this.search) {
					_this.isBookShow = false
				} else {
					_this.isBookShow = true
				}
				await _this.$u.api.saveAndUpdate({
					bookName: _this.bookName,
					bookAvatar: _this.bookAvatar,
					userAudit: _this.audit ? 1 : 0,
					showSearch: _this.search ? 1 : 0,
					budget: _this.budget,
					defaultBook: _this.def ? 1 : 0,
					id: _this.bookId
				}).then((res) => {
					_this.showPopup = false
					_this.isLoad = false
					_this.$u.toast('提交成功')
					_this.get()
				}).catch(() => {
					_this.isLoad = false
					uni.hideLoading()
				})
			},
			//创建者点击成员列表右键
			showActionSheet(i) {
				_this.showAction = true
				_this.userId = _this.list[i].userId
				//创建者
				if (_this.isBookAuthorInfo.auth == 2 && _this.list[i].auth == 2) {
					_this.actionList = [{
						text: '解散账本',
						color: 'red',
						subText: '解散后账本不可恢复，账单信息将删除'
					}]
				} else if (_this.isBookAuthorInfo.auth == 1 && _this.list[i].auth == 0) {
					_this.actionList = [{
						text: '移除Ta',
						color: 'red',
						subText: '账本账单将删除，重新加入后可恢复'
					}]
				} else if (_this.isBookAuthorInfo.auth == 2 && _this.list[i].auth == 0) {
					_this.actionList = [{
						text: '设置Ta为管理员',
						color: '#19be6b ',
						subText: '设置为管理员将有权限管理该账本成员'
					}, {
						text: '移除Ta',
						color: 'red',
						subText: '账本账单将删除，重新加入后可恢复'
					}]
				} else if (_this.isBookAuthorInfo.auth == 2 && _this.list[i].auth == 1) {
					_this.actionList = [{
						text: '移除Ta为管理员',
						color: '#19be6b ',
						subText: '移除管理员将有无权限管理该账本成员'
					}, {
						text: '移除Ta',
						color: 'red',
						subText: '账本账单将删除，重新加入后可恢复'
					}]
				}
			},
			//私密开关改变时候
			searchChange(index) {
				console.log("index:" + index)
				if (index) {
					_this.isAudit = true
					_this.audit = false
				} else {
					_this.isAudit = false
					_this.audit = _this.auditEmp
				}
			},
			//点击操作菜单信息
			touchList(index) {
				console.log("index:" + index)
				if (_this.actionList[index].text == '解散账本') {
					if (_this.list.length > 1) {
						this.$refs.uTips.show({
							title: '还有成员，不可解散账本',
							type: 'error',
							duration: '2300'
						})
					} else {
						_this.deleteBook()
					}
				} else if (_this.actionList[index].text == '设置Ta为管理员') {
					_this.addAdmin()
				} else if (_this.actionList[index].text == '移除Ta为管理员') {
					_this.removeAdmin()
				} else {
					//移除
					_this.remove()
				}
			},
			//删除成员
			async remove() {
				await _this.$u.api.remove({
					bookId: _this.bookId,
					editUserId: _this.userId
				}).then(res => {
					this.$refs.uTips.show({
						title: '删除成员成功',
						type: 'warning',
						duration: '2300'
					})
					//重新获取账本信息
					_this.get()
				});
			},
			//添加成员为管理员
			async addAdmin() {
				await _this.$u.api.addAdmin({
					bookId: _this.bookId,
					editUserId: _this.userId
				}).then(res => {
					this.$refs.uTips.show({
						title: '添加成管理员成功',
						type: 'warning',
						duration: '2300'
					})
					//重新获取账本信息
					_this.get()
				});
			},
			//移除管理员
			async removeAdmin() {
				await _this.$u.api.removeAdmin({
					bookId: _this.bookId,
					editUserId: _this.userId
				}).then(res => {
					this.$refs.uTips.show({
						title: '移除管理员成功',
						type: 'warning',
						duration: '2300'
					})
					//重新获取账本信息
					_this.get()
				});
			},
			//解散账本
			async deleteBook() {
				uni.showLoading({
					title: '正在解散当前账本'
				})
				await _this.$u.api.deleteBook({
					bookId: _this.bookId
				}).then(res => {
					_this.goTabbarUrl('/pages/app/index')
				});
			},
			//跳转到tabbar
			goTabbarUrl(path) {
				uni.switchTab({
					url: path
				});
			},
			chooseAvatar() {
				_this.$u.route({
					url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					params: {
						destWidth: 150,
						rectWidth: 150,
						fileType: 'jpg',
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-bg {
		background-color: $u-bg-color;
	}

	.u-bg-primary {
		background-color: $u-type-success;
	}

	.u-bg-fff {
		background-color: #FFFFFF;
		border-radius: 15px;
	}

	.u-header {
		width: 100rpx;
		height: 100rpx;
		overflow: hidden;
		margin: 0 auto;
	}

	.top-bg {
		height: 100rpx;
		margin-bottom: -100rpx;
	}

	.height-70 {
		height: 70rpx;
		line-height: 70rpx;
	}
</style>